package icu.javayanglei.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import icu.javayanglei.entity.Article;
import icu.javayanglei.service.IArticleService;
import icu.javayanglei.util.qiniu.inter.IQiniuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 文章控制层
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-10-30 17:05
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleMapper;
    @Autowired
    private IQiniuService qiniuService;

    @GetMapping("/toEditor")
    public String toEditor() {
        return "editor";
    }

    @PostMapping("/addArticle")
    public String addArticle(Article article) {
        articleMapper.save(article);
        return "editor";
    }

    /**
     * 博客图片上传
     *
     * @param file    上传的文件
     * @param request 域对象
     * @return json
     * @throws IOException io 异常
     */
    @RequestMapping("/file/upload")
    @ResponseBody
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {

        // 上传图片到七牛服务器，文件名为 唯一id + 原始文件名
        final String s = qiniuService.uploadFile(file, IdUtil.simpleUUID()+file.getOriginalFilename());
        //给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url", s);
        res.put("success", 1);
        res.put("message", "upload success!");
        return res;
    }

    /**
     * 显示文章
     *
     * @param id    文章 id
     * @param model model
     * @return 视图
     */
    @GetMapping("/{id}")
    public String show(@PathVariable("id") int id, Model model) {
        Article article = articleMapper.getById(id);
        model.addAttribute("article", article);
        return "article";
    }
}
